package org.protobuf.chapter2;

import org.protobuf.chapter2.SubscribeRespProto.SubscribeResp;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 
 * @Description	ChannelInboundHandlerAdapter是netty4版本使用方式，ChannelHandlerAdapter是netty5版本使用方式
 * @ClassName	SubReqServerHandler
 * @Date		2018年1月16日 下午1:35:40
 * @Author		liangjl
 * @Copyright (c) All Rights Reserved, 2018.
 */
@Sharable
public class SubReqServerHandler extends ChannelInboundHandlerAdapter{ //ChannelHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		SubscribeReqProto.SubscribeReq req = (SubscribeReqProto.SubscribeReq) msg;
		
		System.out.println(req.getUserName());
		if ("Lilinfeng".equalsIgnoreCase(req.getUserName())) {
			System.out.println("Service accept client subscribe req : [" + req.toString() + "]");
			ctx.writeAndFlush(resp(req.getSubReqID()));
		}
	}

	private SubscribeResp resp(int subReqID) {
		SubscribeRespProto.SubscribeResp.Builder builder = SubscribeRespProto.SubscribeResp.newBuilder();
		builder.setSubReqID(subReqID);
		builder.setRespCode(0);
		builder.setDesc("Netty book order succeed, 3 days later, sent to the designated address");
		return builder.build();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();// 发生异常，关闭链路
	}
}